package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

@Configuration
public class MqttConfiguration {
    @Autowired
    private MqttContext mqttContext;

    private String username="admin";
    private String password="public";
    private String host="tcp://127.0.0.1:1883";
    private String clientId="orderServiceId_"+getRandom();

    public Integer getRandom() {
        Random random=new Random();
        return random.nextInt(100)+1;
    }


    @Bean
    public MqttClient mqttClient(){
        try {
//            创建连接客户端
            MqttClient mqttClient=new MqttClient(host,clientId);
//            创建连接对象的信息
            MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
            mqttConnectOptions.setUserName(username);
            mqttConnectOptions.setPassword(password.toCharArray());
            mqttConnectOptions.setCleanSession(true);
            mqttConnectOptions.setAutomaticReconnect(true);
            mqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);


            MqttConsumer mqttConsumer=new MqttConsumer(mqttClient,mqttContext);
            mqttClient.setCallback(mqttConsumer);
//             使用客户端以及连接信息对象进行连接
            mqttClient.connect(mqttConnectOptions);

            return mqttClient;
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }


    }

}
